import 'dart:convert';
import 'dart:io';

import 'dart:convert' as convert;
import 'package:http/http.dart' as http;

import 'package:json_annotation/json_annotation.dart';
part 'http_client.g.dart';

class DocSystem {
  int id;
  String title;
  String info;
  int cateId;

  DocSystem({required this.id, required this.title, required this.info, required this.cateId});

  factory DocSystem.fromJson(Map<String, dynamic> json) {
    return DocSystem(
      id: json["id"],
      title: json['title'],
      info: json['info'],
      cateId: json['cateId']
    );
  }

  @override
  String toString() {
    return "id: $id, title: $title, info: $info, cateId: $cateId";
  }
}

void _httpExam() async {
  var url =
  Uri.http('localhost:8012', '/doc/system/all');

  // Await the http get response, then decode the json-formatted response.
  var response = await http.get(url);
  if (response.statusCode == 200) {
    // 转换 utf-8 编码
    var responseText = utf8.decode(response.bodyBytes);
    // 转换成 json
    var jsonResponse = convert.jsonDecode(responseText) as Map<String, dynamic>;
    // 获取其中某一项
    var data = jsonResponse["msg"];
    print('通过 http 请求数据: $data.');
  } else {
    print('Request failed with status: ${response.statusCode}.');
  }
}

// 异步请求
void _asyncDemo({required String url}) async {
  HttpClient httpClient = HttpClient();
  HttpClientRequest request = await httpClient.getUrl(Uri.parse(url));

  // 中间处理: 比如添加请求头
  request.headers.add("name", "value");

  HttpClientResponse response = await request.close();
  String responseText = await response.transform(const Utf8Decoder()).join();
  print(responseText);
}

// 调用接口,json 转换
Future<DocSystem> _fetchGet() async {
  final response = await http.get(Uri.http('localhost:8012', '/doc/system/all'));
  var resText = utf8.decode(response.bodyBytes);
  var jsonText = json.decode(resText);

  if (response.statusCode == 200) {
    // 响应成功
    return DocSystem.fromJson(jsonText["data"][0]);
  }

  throw Exception("Failed to load data.");
}

@JsonSerializable()
class DocCate {
  final int id;
  final String title;
  final String info;
  final String bgColor;
  final int sysId;
  final int linkId;

  DocCate({required this.id,
    required this.title,
    required this.info,
    required this.bgColor,
    required this.sysId,
    required this.linkId});

  factory DocCate.fromJson(Map<String, dynamic> json) => _$DocCateFromJson(json);

  @override
  String toString() {
    return "id: $id, title: $title, info: $info, bgColor: $bgColor, sysId: $sysId, linkId: $linkId";
  }
}

Future<DocCate> _fetchGetCate() async{
  final response = await http.get(Uri.http('localhost:8012', '/doc/cate/all'));
  var resText = utf8.decode(response.bodyBytes);
  var jsonText = json.decode(resText);
  if (response.statusCode == 200) {
    // 响应成功
    return DocCate.fromJson(jsonText["data"][0]);
  }

  throw Exception("Failed to load data.");
}

void main() async {
   var res = await _fetchGetCate();
   print(res);
}